package cn.yh.kettle_service.master.service;

import cn.yh.kettle_service.utils.Results;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.job.Job;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;
import org.quartz.CronScheduleBuilder;
import org.quartz.CronTrigger;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.JobKey;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class KettleJobService {

    private final Scheduler scheduler;

    private final Map<String, JobKey> runningJobs = new HashMap<>();

    @Autowired
    public KettleJobService(SchedulerFactoryBean factoryBean) throws SchedulerException {
        this.scheduler = factoryBean.getScheduler();
    }

    public Results<String> scheduleJob(String jobName, String filePath, String cron) throws Exception {
        try {
            if (cron == null || cron.trim().isEmpty()) {
                // 立即执行一次
                runKettleNow(filePath);
                return Results.success("执行成功");
            }

            if (runningJobs.containsKey(jobName)) {
                return Results.fail("任务" + filePath + "已存在");
            }

            JobDetail jobDetail = JobBuilder.newJob(KettleQuartzJob.class)
                    .withIdentity(jobName)
                    .usingJobData("filePath", filePath)
                    .build();

            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(jobName + "_trigger")
                    .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                    .build();

            scheduler.scheduleJob(jobDetail, trigger);
            runningJobs.put(jobName, jobDetail.getKey());
            return Results.success("任务已调度" + jobName);

        } catch (Exception e) {
            return Results.fail("任务调度失败" + e.getMessage());
        }
    }

    public Results<List<String>> listRunningJobs() {
        try {
            return Results.success(new ArrayList<>(runningJobs.keySet()));
        } catch (Exception e) {
            return Results.fail("任务列表获取失败" + e.getMessage());
        }
    }

    public Results<String> deleteJob(String jobName) throws SchedulerException {
        try {
            JobKey key = runningJobs.remove(jobName);
            if (key != null) {
                scheduler.deleteJob(key);
            }
            return Results.success("已移除: " + jobName + " 任务");
        } catch (SchedulerException e) {
            return Results.fail("移除接口异常" + e.getMessage());
        }
    }

    public static void runKettleNow(String filePath) throws Exception {
        KettleEnvironment.init();
        if (filePath.endsWith(".kjb")) {
            JobMeta jobMeta = new JobMeta(filePath, null);
            Job job = new Job(null, jobMeta);
            job.start();
            job.waitUntilFinished();
        } else if (filePath.endsWith(".ktr")) {
            TransMeta transMeta = new TransMeta(filePath);
            Trans trans = new Trans(transMeta);
            trans.execute(null);
            trans.waitUntilFinished();
        } else {
            throw new IllegalArgumentException("只支持 .kjb 或 .ktr 文件");
        }
    }
}

